import { Application } from 'egg';
import { DataTypes, Model } from 'sequelize';

export type ExclusiveOrderStatus = 'pending' | 'accepted' | 'rejected' | 'cancelled';

export interface ExclusiveOrderAttributes {
  id?: number;
  restaurant_id: number;
  user_id: number; // 下单用户（即 user_id）
  status: ExclusiveOrderStatus;
  remark?: string;
  created_at?: Date;
  updated_at?: Date;
}

export interface ExclusiveOrderInstance extends Model<ExclusiveOrderAttributes>, ExclusiveOrderAttributes {}

export default (app: Application) => {
  const { STRING, INTEGER, ENUM, DATE } = DataTypes;

  const ExclusiveOrder = app.model.define<ExclusiveOrderInstance>('ExclusiveOrder', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    restaurant_id: { type: INTEGER, allowNull: false, comment: '专属餐厅ID' },
    user_id: { type: INTEGER, allowNull: false, comment: '下单用户ID' },
    status: { type: ENUM('pending', 'accepted', 'rejected', 'cancelled'), allowNull: false, defaultValue: 'pending', comment: '订单状态' },
    remark: { type: STRING(255), allowNull: true, comment: '备注' },
    created_at: { type: DATE, allowNull: false, defaultValue: DataTypes.NOW },
    updated_at: { type: DATE, allowNull: false, defaultValue: DataTypes.NOW },
  }, {
    tableName: 'exclusive_orders',
    comment: '专属餐厅订单表',
  });

  (ExclusiveOrder as any).associate = () => {
    app.model.ExclusiveOrder.belongsTo(app.model.ExclusiveRestaurant, { foreignKey: 'restaurant_id', as: 'restaurant' });
    app.model.ExclusiveOrder.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
    app.model.ExclusiveOrder.hasMany(app.model.ExclusiveOrderItem, { foreignKey: 'order_id', as: 'order_dishs' });
  };

  return ExclusiveOrder;
};